<template>
  <div></div>
</template>

<script>
import { authLoginByWeixin } from '@/api/api';
import { getLocalStorage, setLocalStorage } from '@/utils/local-storage';
import { Toast } from 'vant';
/**
 * 微信网页授权
 */
export default {
  name: 'auth',

  data() {
    return {
      wxCode: '',
      directorOpenId: null,
    };
  },

  created() {
    this.loginByWeixin();
  },

  methods: {
    loginByWeixin() {
      let { shareId } = getLocalStorage('shareId');
      // 如果连接中有微信返回的 code，则用此 code 调用后端接口，向微信服务器请求用户信息
      // 如果不是从微信重定向过来的，没有带着微信的 code，则直接进入首页
      this.codeSearch();
      authLoginByWeixin({
        code: this.wxCode,
        directorOpenId: this.directorOpenId,
        shareId: shareId,
      })
        .then((res) => {
          setLocalStorage({
            Authorization: res.data.data.token,
            avatar: res.data.data.userInfo.headImgUrl,
            nickName: res.data.data.userInfo.nickname,
            mobile: res.data.data.ttmallUser.mobile,
            userId: res.data.data.ttmallUser.id,
          });
          const beforeUrl = getLocalStorage('beforeUrl');
          //console.log(beforeUrl.beforeUrl)
          window.location.href =
            process.env.VUE_APP_BASE_API + 'wechat/#' + beforeUrl.beforeUrl;
          this.$router.replace(beforeUrl.beforeUrl);
        })
        .catch((error) => {
          Toast.fail(error.data.errmsg);
        });
    },
    codeSearch() {
      let name,
        value,
        str = window.location.href,
        num = str.indexOf('?'); //取得整个地址栏
      str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
      let arr = str.split('&'); //各个参数放到数组里
      //alert(JSON.stringify(arr));
      for (let i = 0; i < arr.length; i++) {
        num = arr[i].indexOf('=');
        if (num > 0) {
          name = arr[i].substring(0, num);
          value = arr[i].substr(num + 1);
          if (name == 'code') {
            this.wxCode = value;
          }
          if (name == 'directorOpenId') {
            this.directorOpenId = value;
          }
        }
      }
    },
  },
};
</script>
